package com.core.db.require;

import java.sql.SQLException;
import java.util.List;

import com.core.db.condition.Condition;

class Select extends BaseRequire
{
	private List< ColumnDescribe > describes;
	private Condition cond;
	private String table;

	public Select( String table, List< ColumnDescribe > describes, Condition cond )
	{
		this.table = table;
		this.describes = describes;
		this.cond = cond;
	}

	@Override
	public String sql() throws SQLException
	{
		if ( cond == null || table == null || table.length() == 0 )
		{
			throw new SQLException( "No table to be found to be operated on" );
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append( "SELECT " );
		buffer.append( assembleColumns( getColumns() ) );
		buffer.append( " FROM " ).append( table );
		buffer.append( " " ).append( assembleWhere( cond ) );
		buffer.append( " " ).append( assembleOrder( cond ) );
		return buffer.toString();
	}

	@Override
	public Condition getCondition()
	{
		return this.cond;
	}

	@Override
	public List< ColumnDescribe > getColumnDescribes()
	{
		return this.describes;
	}
	
	@Override
	protected String assembleColumns( List< String > columns )
	{
		StringBuffer buffer = new StringBuffer();
		if ( columns == null || columns.size() == 0 )
		{
			buffer.append( "*" );
		}
		else
		{
			int maxIndex = columns.size() - 1;
			for ( int i = 0; i < maxIndex; i++ )
			{
				buffer.append( columns.get( i ) ).append( "," );
			}
			buffer.append( columns.get(maxIndex) );
		}
		return buffer.toString();
	}
}
